import {
  deleteImage,
  getDockerDocs,
  getDockerStatus,
  getDockerVersion,
  importImage,
  listImages,
  pullImage,
  restartDocker,
  startDocker,
  stopDocker,
  tagImage,
  uploadImage,
} from '@/services/docker/DockerInfoController';
import { getArchitectureColor, getColorByString } from '@/utils/colors';
import { formatTimeAgo } from '@/utils/format';
import {
  ApiOutlined,
  ContainerOutlined,
  DeleteOutlined,
  DesktopOutlined,
  LinkOutlined,
  PlusOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import {
  PageContainer,
  ProCard,
  StatisticCard,
} from '@ant-design/pro-components';
import {
  Badge,
  Button,
  Card,
  Col,
  Empty,
  Input,
  message,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tag,
  Tooltip,
  Upload,
} from 'antd';
import React, { useEffect, useState } from 'react';
import CustomStatisticCard from './components/CustomStatisticCard';
import { PATH_PREFIXES, TABLE_PAGINATION } from './constants';
import styles from './index.less';

// 获取Docker镜像列表
const fetchDockerImages = async (): Promise<API.DockerImageVO[] | null> => {
  try {
    const response = await listImages();
    if (!response.success) throw new Error('Network response was not ok');
    return response.data || null;
  } catch (error) {
    console.error('获取Docker镜像失败:', error);
    return null;
  }
};

// 获取Docker版本信息
const fetchDockerVersion = async (): Promise<API.DockerVersionVO | null> => {
  try {
    const response = await getDockerVersion();
    if (!response.success) throw new Error('Network response was not ok');
    return response.data || null;
  } catch (error) {
    console.error('获取Docker版本失败:', error);
    return null;
  }
};

// 获取Docker文档
const fetchDockerDoc = async (): Promise<API.DockerDocVO[] | null> => {
  try {
    const response = await getDockerDocs();
    if (!response.success) throw new Error('Network response was not ok');
    return response.data || null;
  } catch (error) {
    console.error('获取Docker文档失败:', error);
    return null;
  }
};

const DockerPanel: React.FC = () => {
  const [images, setImages] = useState<API.DockerImageVO[] | null>(null);
  const [versionInfo, setVersionInfo] = useState<API.DockerVersionVO | null>(
    null,
  );
  const [loading, setLoading] = useState<boolean>(true);
  const [pullModalVisible, setPullModalVisible] = useState(false);
  const [imageName, setImageName] = useState('');
  const [uploading, setUploading] = useState(false);
  const [docs, setDocs] = useState<API.DockerDocVO[] | null>(null);
  const [pathModalVisible, setPathModalVisible] = useState(false);
  const [importPath, setImportPath] = useState('');
  const [tagModalVisible, setTagModalVisible] = useState(false);
  const [currentImageId, setCurrentImageId] = useState('');
  const [newTag, setNewTag] = useState('');
  const [selectedPrefix, setSelectedPrefix] = useState('W');
  const [pathValue, setPathValue] = useState('');
  const [tagImageName, setTagImageName] = useState('');
  const [tagVersion, setTagVersion] = useState('');
  const [serviceStatus, setServiceStatus] =
    useState<API.DockerServiceStatusVO | null>(null);
  const [serviceLoading, setServiceLoading] = useState(false);

  // 添加服务操作函数
  const handleServiceOperation = async (
    operation: 'start' | 'stop' | 'restart',
  ) => {
    setServiceLoading(true);
    try {
      const api = {
        start: startDocker,
        stop: stopDocker,
        restart: restartDocker,
      }[operation];

      const response = await api();
      if (response.success) {
        message.success(
          `Docker服务${
            operation === 'start'
              ? '启动'
              : operation === 'stop'
              ? '停止'
              : '重启'
          }成功`,
        );
        // 刷新服务状态
        const statusResponse = await getDockerStatus();
        if (statusResponse.success) {
          setServiceStatus(statusResponse.data ? statusResponse.data : null);
        }
        // 如果是启动或重启操作，刷新镜像列表
        if (operation !== 'stop') {
          const images = await fetchDockerImages();
          setImages(images);
        }
      } else {
        message.error(`操作失败: ${response.message}`);
      }
    } catch (error) {
      console.error('Docker服务操作失败:', error);
      message.error('操作失败');
    } finally {
      setServiceLoading(false);
    }
  };

  useEffect(() => {
    const loadData = async () => {
      const [images, versions, docs, status] = await Promise.all([
        fetchDockerImages(),
        fetchDockerVersion(),
        fetchDockerDoc(),
        getDockerStatus(),
      ]);
      setImages(images);
      setVersionInfo(versions);
      setDocs(docs);
      if (status.success) {
        setServiceStatus(status.data ?? null);
      }
      setLoading(false);
    };

    loadData();
  }, []);

  const handlePullImage = async () => {
    if (!imageName) {
      message.warning('请输入镜像名称');
      return;
    }
    setLoading(true);
    try {
      const response = await pullImage({ imageName });
      if (response.success) {
        message.success('镜像拉取成功');
        const images = await fetchDockerImages();
        setImages(images);
        setPullModalVisible(false);
        setImageName('');
      } else {
        message.error('镜像拉取失败');
      }
    } catch (error) {
      console.error('拉取镜像失败:', error);
      message.error('镜像拉取失败');
    } finally {
      setLoading(false);
    }
  };

  const handleUploadImage = async (file: File) => {
    const formData = new FormData();
    formData.append('file', file);
    setUploading(true);
    try {
      const response = await uploadImage(formData);
      if (response.success) {
        message.success('镜像上传成功');
        const images = await fetchDockerImages();
        setImages(images);
      } else {
        message.error('镜像上传失败');
      }
    } catch (error) {
      console.error('上传镜像失败:', error);
      message.error('镜像上传失败');
    } finally {
      setUploading(false);
    }
    return false;
  };

  const handleDeleteImage = async (imageId: string, imageName: string) => {
    let inputImageName = '';

    Modal.confirm({
      title: '确认删除镜像',
      content: (
        <div>
          <p>请输入镜像名称 "{imageName}" 以确认删除:</p>
          <Input
            placeholder="请输入完整的镜像名称"
            onChange={(e) => (inputImageName = e.target.value)}
          />
        </div>
      ),
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        if (inputImageName !== imageName) {
          message.error('输入的镜像名称不匹配');
          return Promise.reject('输入的镜像名称不匹配');
        }

        setLoading(true);
        try {
          const response = await deleteImage({ imageId });
          if (response.success) {
            message.success('镜像删除成功');
            const images = await fetchDockerImages();
            setImages(images);
          } else {
            message.error('镜像删除失败');
          }
        } catch (error) {
          console.error('删除镜像失败:', error);
          message.error('镜像删除失败');
        } finally {
          setLoading(false);
        }
      },
    });
  };

  // 处理路径导入
  const handleImportFromPath = async () => {
    if (!pathValue) {
      message.warning('请输入有效的路径');
      return;
    }

    setLoading(true);
    try {
      const fullPath = `${selectedPrefix}-${pathValue}`;
      const response = await importImage({ path: fullPath });
      if (response.success) {
        message.success('镜像导入成功');
        const images = await fetchDockerImages();
        setImages(images);
        setPathModalVisible(false);
        setPathValue('');
      } else {
        message.error('镜像导入失败');
      }
    } catch (error) {
      console.error('导入镜像失败:', error);
      message.error('镜像导入失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理打标签
  const handleTagImage = async () => {
    if (!tagImageName || !tagVersion) {
      message.warning('请输入镜像名称和标签');
      return;
    }

    setLoading(true);
    try {
      const fullTag = `${tagImageName}:${tagVersion}`;
      const response = await tagImage({
        imageId: currentImageId,
        newTag: fullTag,
      });
      if (response.success) {
        message.success('标签添加成功');
        const images = await fetchDockerImages();
        setImages(images);
        setTagModalVisible(false);
        setTagImageName('');
        setTagVersion('');
      } else {
        message.error('标签添加失败');
      }
    } catch (error) {
      console.error('添加标签失败:', error);
      message.error('标签添加失败');
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '镜像ID',
      dataIndex: 'id',
      key: 'id',
      render: (id: string) => <span>{id.substring(0, 12)}</span>,
    },
    {
      title: '镜像名称',
      dataIndex: 'name',
      key: 'name',
      render: (name: string, record: API.DockerImageVO) => (
        <span>
          {name}:{record.tag}
        </span>
      ),
    },
    {
      title: '架构',
      dataIndex: 'architecture',
      key: 'architecture',
      render: (architecture: string) => (
        <Tag color={getArchitectureColor(architecture)}>{architecture}</Tag>
      ),
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
    },
    {
      title: '创建时间',
      dataIndex: 'created',
      key: 'created',
      render: (created: string) => (
        <Tooltip title={new Date(created).toLocaleString('zh-CN')}>
          <span>{formatTimeAgo(created)}</span>
        </Tooltip>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: API.DockerImageVO) => (
        <Space>
          <Button
            danger
            icon={<DeleteOutlined />}
            onClick={() =>
              handleDeleteImage(record.id, `${record.name}:${record.tag}`)
            }
          >
            删除
          </Button>
          {(record.name === '<none>' || record.tag === '<none>') && (
            <Button
              type="primary"
              onClick={() => {
                setCurrentImageId(record.id);
                setTagModalVisible(true);
              }}
            >
              打标签
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <PageContainer ghost header={{ title: 'Docker环境' }}>
      {/* Docker服务状态卡片组 */}
      <StatisticCard.Group direction="row">
        <StatisticCard
          statistic={{
            title: 'Docker服务状态',
            value: serviceStatus?.status === 'running' ? '运行中' : '已停止',
            status: serviceStatus?.status === 'running' ? 'success' : 'error',
            prefix: (
              <Badge
                status={
                  serviceStatus?.status === 'running' ? 'success' : 'error'
                }
              />
            ),
          }}
        />
        <StatisticCard.Divider type="vertical" />
        <StatisticCard title={'🪄基础操作'}>
          <Space>
            <Button
              type="primary"
              danger={serviceStatus?.status === 'running'}
              loading={serviceLoading}
              onClick={() =>
                handleServiceOperation(
                  serviceStatus?.status === 'running' ? 'stop' : 'start',
                )
              }
            >
              {serviceStatus?.status === 'running' ? '停止服务' : '启动服务'}
            </Button>
            <Button
              loading={serviceLoading}
              onClick={() => handleServiceOperation('restart')}
              disabled={serviceStatus?.status !== 'running'}
            >
              重启服务
            </Button>
          </Space>
        </StatisticCard>
        <StatisticCard.Divider type="vertical" />
        <StatisticCard title={'❤️基础设置'}>
          {versionInfo && (
            <Space>
              <Button
                color="danger"
                variant="outlined"
                onClick={() => alert('设置国内源')}
              >
                设置国内源
              </Button>
              <Button
                color="pink"
                variant="outlined"
                onClick={() => alert('设置日志')}
              >
                日志配置
              </Button>
              <Button
                color="purple"
                variant="outlined"
                onClick={() => alert('设置网络')}
              >
                网络配置
              </Button>
            </Space>
          )}
        </StatisticCard>
      </StatisticCard.Group>
      {versionInfo && (
        <StatisticCard.Group direction="row" style={{ marginTop: 16 }}>
          <CustomStatisticCard
            title="Docker 版本"
            value={versionInfo.dockerVersion}
            icon={
              <ContainerOutlined
                style={{
                  fontSize: '24px',
                  color: '#1890ff',
                }}
              />
            }
            maxWidth={150}
            placement="top"
          />

          <StatisticCard.Divider type="vertical" />

          <CustomStatisticCard
            title="系统版本"
            value={versionInfo.osVersion}
            icon={
              <DesktopOutlined
                style={{
                  fontSize: '24px',
                  color: '#52c41a',
                }}
              />
            }
            maxWidth={240}
            placement="top"
          />

          <StatisticCard.Divider type="vertical" />

          <CustomStatisticCard
            title="Compose 版本"
            value={versionInfo.composeVersion}
            icon={
              <ApiOutlined
                style={{
                  fontSize: '24px',
                  color: '#722ed1',
                }}
              />
            }
            maxWidth={150}
            placement="top"
          />
          <StatisticCard />
        </StatisticCard.Group>
      )}

      <Row gutter={16} style={{ marginTop: 16 }}>
        <Col span={16}>
          <Card
            title="镜像列表"
            extra={
              versionInfo && (
                <Space>
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={() => setPullModalVisible(true)}
                  >
                    拉取镜像
                  </Button>
                  <Button onClick={() => setPathModalVisible(true)}>
                    目录镜像
                  </Button>
                  <Upload
                    accept=".tar,.tar.gz"
                    beforeUpload={handleUploadImage}
                    showUploadList={false}
                  >
                    <Button icon={<UploadOutlined />} loading={uploading}>
                      上传镜像
                    </Button>
                  </Upload>
                </Space>
              )
            }
          >
            {!images && loading ? (
              <Empty description="加载中..." />
            ) : images && images.length > 0 ? (
              <Table
                dataSource={images}
                columns={columns}
                loading={loading}
                rowKey="id"
                pagination={TABLE_PAGINATION}
              />
            ) : (
              <Empty
                description="未检测到 Docker 镜像"
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            )}
          </Card>
        </Col>

        <Col span={8}>
          <ProCard
            title="相关文档"
            headerBordered
            bordered
            direction="column"
            gutter={[0, 16]}
          >
            <div className={styles['docs-scroll-container']}>
              <ProCard
                gutter={[16, 16]}
                wrap
                style={{
                  padding: '0px',
                  margin: 0,
                }}
                bodyStyle={{
                  padding: 0,
                }}
              >
                {docs?.map((doc: API.DockerDocVO, index: number) => (
                  <Badge.Ribbon
                    key={index}
                    text={doc.type}
                    color={getColorByString(doc.type)}
                  >
                    <ProCard
                      colSpan={24}
                      layout="center"
                      bordered
                      hoverable
                      onClick={() => window.open(doc.url, '_blank')}
                      style={{
                        marginBottom: '16px',
                      }}
                    >
                      <Space
                        align="start"
                        style={{
                          width: '100%',
                          padding: '8px 0',
                        }}
                      >
                        <LinkOutlined
                          style={{
                            fontSize: '20px',
                            marginTop: '4px',
                            marginRight: '12px',
                          }}
                        />
                        <div style={{ flex: 1 }}>
                          <div
                            style={{
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'center',
                            }}
                          >
                            <span
                              style={{
                                fontWeight: 'bold',
                                fontSize: '16px',
                                lineHeight: '24px',
                              }}
                            >
                              {doc.title}
                            </span>
                          </div>
                          <div
                            style={{
                              color: '#666',
                              marginTop: '4px',
                              lineHeight: '20px',
                            }}
                          >
                            {doc.description}
                          </div>
                        </div>
                      </Space>
                    </ProCard>
                  </Badge.Ribbon>
                ))}
              </ProCard>
            </div>
          </ProCard>
        </Col>
      </Row>

      <Modal
        title="拉取镜像"
        open={pullModalVisible}
        onOk={handlePullImage}
        onCancel={() => setPullModalVisible(false)}
        confirmLoading={loading}
      >
        <Input
          placeholder="请输入镜像名称，如: nginx:latest"
          value={imageName}
          onChange={(e) => setImageName(e.target.value)}
        />
      </Modal>

      {/* 添加新的模态框 */}
      <Modal
        title="设置导入目录"
        open={pathModalVisible}
        onOk={handleImportFromPath}
        onCancel={() => setPathModalVisible(false)}
        confirmLoading={loading}
      >
        <Space.Compact style={{ width: '100%' }}>
          <Select
            value={selectedPrefix}
            onChange={setSelectedPrefix}
            style={{ width: '120px' }}
          >
            {PATH_PREFIXES.map((prefix) => (
              <Select.Option key={prefix.value} value={prefix.value}>
                {prefix.label}
              </Select.Option>
            ))}
          </Select>
          <Input
            placeholder="请输入路径"
            value={pathValue}
            onChange={(e) => setPathValue(e.target.value)}
            style={{ flex: 1 }}
          />
        </Space.Compact>
      </Modal>

      {/* 标签添加模态框 */}
      <Modal
        title="设置标签"
        open={tagModalVisible}
        onOk={handleTagImage}
        onCancel={() => setTagModalVisible(false)}
        confirmLoading={loading}
      >
        <Space direction="vertical" style={{ width: '100%' }} size="small">
          <Row>
            <Col span={12}>
              <div style={{ paddingRight: 8 }}>
                <div style={{ marginBottom: 8 }}>镜像名称</div>
                <Input
                  placeholder="请输入镜像名称"
                  value={tagImageName}
                  onChange={(e) => setTagImageName(e.target.value)}
                />
              </div>
            </Col>
            <Col span={12}>
              <div style={{ paddingLeft: 8 }}>
                <div style={{ marginBottom: 8 }}>标签版本</div>
                <Input
                  placeholder="请输入标签版本"
                  value={tagVersion}
                  onChange={(e) => setTagVersion(e.target.value)}
                />
              </div>
            </Col>
          </Row>
        </Space>
      </Modal>
    </PageContainer>
  );
};

export default DockerPanel;
